package cn.school.controller.logistics;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.exception.ApiException;
import cn.school.common.utils.SysUserUtils;
import cn.school.logistics.entity.Assets;
import cn.school.logistics.entity.AssetsCollect;
import cn.school.logistics.entity.AssetsStoreDetils;
import cn.school.logistics.service.AssetsCollectService;
import cn.school.logistics.service.AssetsService;
import cn.school.logistics.service.AssetsStoreDetilsService;
import cn.school.sys.entity.SysUserRole;
import cn.school.sys.service.SysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * 资产领取
 * @className: AssetsCollectController
 * @author: fangjin.tao
 * @date: 2022/12/9
 **/
@RestController
@Api(tags = "AssetsCollectController => 资产领取管理")
@RequestMapping("/logistics/assetsCollect")
public class AssetsCollectController {
	@Autowired
	private AssetsCollectService assetsCollectService;
	@Autowired
	private AssetsService assetsService;
	@Autowired
	private AssetsStoreDetilsService assetsStoreDetilsService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@ApiOperation("获取列表")
	@GetMapping("/list")
	public CommonResult<CommonPage<AssetsCollect>> list(@RequestParam Map<String, Object> para) {
		// 条件获取
		int pageNum = Integer.parseInt((String) para.get("pageNum"));
		int pageSize = Integer.parseInt((String) para.get("pageSize"));
		
		String ascoCollectTime = (String) para.get("ascoCollectTime"); // 领用日期
		String ascoBeginCollectTime = (String) para.get("ascoBeginCollectTime"); // 领用查询-领用时间-左区间（开始）
		String ascoEndCollectTime = (String) para.get("ascoBeginCollectTime"); // 领用查询-领用时间-右区间（结束）
		String asseId = (String) para.get("asseId"); // 资产ID
		String asseName = (String) para.get("asseName"); // 资产名称
		String ascoCollectUserName = (String) para.get("ascoCollectUserName"); // 申领人
		String ascoCollectStatus = (String) para.get("ascoCollectStatus"); // 申领状态
		String ascoExamineUserName = (String) para.get("ascoExamineUserName"); // 申审人
		
		
		Page<AssetsCollect> page = new Page<>();
		page.setSize(pageSize);
		page.setCurrent(pageNum);
		
		// queryWrapper查询设置
		LambdaQueryWrapper<AssetsCollect> queryWrapper = new LambdaQueryWrapper<>();
		if (StrUtil.isNotEmpty(asseId)) {
			queryWrapper.eq(AssetsCollect::getAsseId, asseId);
		}
		if (StrUtil.isNotEmpty(ascoCollectTime)) {
			// 具体日期
			queryWrapper.ge(AssetsCollect::getAscoCollectTime, DateUtil.parse(ascoCollectTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
			queryWrapper.le(AssetsCollect::getAscoCollectTime, DateUtil.parse(ascoCollectTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
		}
		if (StrUtil.isNotEmpty(ascoBeginCollectTime)) {
			queryWrapper.ge(AssetsCollect::getAscoCollectTime, DateUtil.parse(ascoBeginCollectTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
		}
		if (StrUtil.isNotEmpty(ascoEndCollectTime)) {
			queryWrapper.le(AssetsCollect::getAscoCollectTime, DateUtil.parse(ascoEndCollectTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
		}
		if (StrUtil.isNotEmpty(asseName)) {
			queryWrapper.like(AssetsCollect::getAsseName, asseName);
		}
		if (StrUtil.isNotEmpty(ascoCollectUserName)) {
			queryWrapper.like(AssetsCollect::getAscoCollectUserName, ascoCollectUserName);
		}
		if (StrUtil.isNotEmpty(ascoCollectStatus)) {
			queryWrapper.eq(AssetsCollect::getAscoCollectStatus, ascoCollectStatus);
		}
		if (StrUtil.isNotEmpty(ascoExamineUserName)) {
			queryWrapper.like(AssetsCollect::getAscoExamineUserName, ascoExamineUserName);
		}
		//租户
		queryWrapper.eq(AssetsCollect::getTenantId, SysUserUtils.getSysUser().getTenantId());
		// 查询
		queryWrapper.orderByAsc(AssetsCollect::getAscoCollectStatus);
		queryWrapper.orderByDesc(AssetsCollect::getAscoCollectTime);
		IPage<AssetsCollect> iPage = this.assetsCollectService.page(page, queryWrapper);
		
		// 判断教务角色的ID，加上按钮展示字段
		if (iPage.getRecords() != null && iPage.getRecords().size() != 0) {
			LambdaQueryWrapper<SysUserRole> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
			roleLambdaQueryWrapper.eq(SysUserRole::getUserId, SysUserUtils.getSysUser().getId());
			roleLambdaQueryWrapper.eq(SysUserRole::getRoleId, 9L);
			int countLogisticsRole = this.sysUserRoleService.count(roleLambdaQueryWrapper);
			if (countLogisticsRole != 0) {
				for (AssetsCollect record : iPage.getRecords()) {
					record.setExamineBtmRight(true);
				}
			}
		}
		
		return CommonResult.success(CommonPage.restPage(iPage));
	}
	
	
	@ApiOperation("获取教材领用详情")
	@GetMapping("/info/{id}")
	public CommonResult<AssetsCollect> getInfoById(@PathVariable Long id) {
		AssetsCollect assetsCollect = this.assetsCollectService.getById(id);
		if (assetsCollect == null) {
			throw new ApiException("领用记录不存在，请刷新页面");
		}
		return CommonResult.success(assetsCollect);
	}
	
	
	@ApiOperation("添加教材领用")
	@PostMapping("/add")
	@Transactional
	public CommonResult<AssetsCollect> add(@RequestBody AssetsCollect assetsCollect) {
		Assets assets = this.assetsService.getById(assetsCollect.getAsseId());
		if (assets == null) {
			throw new ApiException("资产不存在，请刷新页面后重试");
		}
		if (assets.getAsseCount() < assetsCollect.getAscoCollectCount()) {
			throw new ApiException("资产库存不够");
		}
		assetsCollect.setAsseName(assets.getAsseName());
		assetsCollect.setAsseCode(assets.getAsseCode());
		assetsCollect.setAscoCollectTime(Calendar.getInstance().getTime());
		assetsCollect.setAscoCollectUserId(SysUserUtils.getSysUser().getId());
		if (StrUtil.isNotEmpty(SysUserUtils.getSysUser().getSysuName())) {
			assetsCollect.setAscoCollectUserName(SysUserUtils.getSysUser().getSysuName());
		} else {
			assetsCollect.setAscoCollectUserName(SysUserUtils.getSysUser().getUsername());
		}
		assetsCollect.setAscoCollectStatus("0");
		
		
		assetsCollect.setCreateTime(Calendar.getInstance().getTime());
		assetsCollect.setModifyTime(Calendar.getInstance().getTime());
		assetsCollect.setCreateBy(SysUserUtils.getSysUser().getId());
		
		boolean isAddSuccess = this.assetsCollectService.save(assetsCollect);
		if (isAddSuccess) {
			return CommonResult.success();
		} else {
			return CommonResult.failed();
		}
	}
	
	@ApiOperation("审核教材领用")
	@PutMapping("/examine/{id}")
	public CommonResult<AssetsCollect> update(@PathVariable Long id, @RequestBody AssetsCollect assetsCollect) {
		AssetsCollect dbAscoEntity = this.assetsCollectService.getById(id);
		if (dbAscoEntity == null) {
			throw new ApiException("申领记录不存在，请刷新后重试");
		}
		if (!"0".equals(dbAscoEntity.getAscoCollectStatus())) {
			throw new ApiException("申领记录审核不能重复处理，请刷新界面");
		}
		dbAscoEntity.setAscoCollectStatus(assetsCollect.getAscoCollectStatus());
		if ("1".equals(dbAscoEntity.getAscoCollectStatus())) {
			// 审核通过，检查库存数量
			Assets assets = this.assetsService.getById(assetsCollect.getAsseId());
			if (assets == null) {
				throw new ApiException("教材不存在，请刷新页面后重试");
			}
			if (assets.getAsseCount() < assetsCollect.getAscoCollectCount()) {
				throw new ApiException("教材库存不够");
			}
			// 更新库存
			AssetsStoreDetils assetsStoreDetils = new AssetsStoreDetils();
			assetsStoreDetils.setAsseCode(assets.getAsseCode());
			assetsStoreDetils.setAsseName(assets.getAsseName());
			assetsStoreDetils.setAsseId(assets.getId());
			assetsStoreDetils.setAsdeType("0"); //领取出库
			assetsStoreDetils.setAsdeCount(dbAscoEntity.getAscoCollectCount());
			
			// 保存领取记录
			assetsStoreDetils.setCreateBy(SysUserUtils.getSysUser().getId());
			assetsStoreDetils.setCreateTime(Calendar.getInstance().getTime());
			assetsStoreDetils.setModifyTime(Calendar.getInstance().getTime());
			this.assetsStoreDetilsService.saveBiz(assetsStoreDetils);
			assetsCollect.setAsdeId(assetsStoreDetils.getId());// 库存明细ID
		} else {
			// 不通过时，不做库存操作
		}
		assetsCollect.setAscoExamineTime(Calendar.getInstance().getTime());
		assetsCollect.setAscoExamineUserId(SysUserUtils.getSysUser().getId());
		if (StrUtil.isNotEmpty(SysUserUtils.getSysUser().getSysuName())) {
			assetsCollect.setAscoExamineUserName(SysUserUtils.getSysUser().getSysuName());
		} else {
			assetsCollect.setAscoExamineUserName(SysUserUtils.getSysUser().getUsername());
		}
		
		boolean isUpdateSuccess = this.assetsCollectService.updateById(assetsCollect);
		if (isUpdateSuccess) {
			return CommonResult.success();
		} else {
			return CommonResult.failed();
		}
	}
	
	@ApiOperation("资产选择选择列表")
	@GetMapping("/assets/list")
	public CommonResult<List<Assets>> teachingMaterialList(Map<String, Object> params) {
		String queryAsseCodeOrName = (String) params.get("queryAsseCodeOrName");
		LambdaQueryWrapper<Assets> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Assets::getTenantId, SysUserUtils.getSysUser().getTenantId());
		if (StrUtil.isNotEmpty(queryAsseCodeOrName)) {
			queryWrapper.and((wrapper) -> {
				wrapper.like(Assets::getAsseName, queryAsseCodeOrName.trim());
				wrapper.or().like(Assets::getAsseCode, queryAsseCodeOrName.trim());
			});
		}
		List<Assets> assetslList = this.assetsService.list(queryWrapper);
		return CommonResult.success(assetslList);
	}


//	@ApiOperation("删除领用明细")
//	@DeleteMapping("/deleteByIds/{ids}")
//	public CommonResult<TeachingMaterialCollect> delete(@PathVariable Long[] ids) {
//		List<Long> idList = Arrays.stream(ids).collect(Collectors.toList());
//		boolean isDeleteSuccess = this.teachingMaterialCollectService.removeByIds(idList);
//		if (isDeleteSuccess) {
//			return CommonResult.success();
//		} else {
//			return CommonResult.failed();
//		}
//	}
	
}
